package ru.smc.hogwarts.servlets.rooms;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Room;
import ru.smc.hogwarts.model.Student;

public class RoomsStudents extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
	
	private String error = "";
       
    public RoomsStudents() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		
    	long id = 0;
    	
    	try {
			id = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {}
		
    	EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
    	
		Room room = em.find(Room.class, id);
		
		if (room == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {
			if(room.getFull() == 4) {
				error = "<span>К</span>омната максимально заселена.";
				session.setAttribute("error", error);
				response.sendRedirect(request.getContextPath() + "/rooms/info?id="+id);
			} else {
		    	String action = request.getParameter("search");
				
				if (action != null && action.equals("clear") || (session.getAttribute("servletName") != null && !session.getAttribute("servletName").equals(getServletName()))) {
					session.setAttribute("searchFN", "");
					session.setAttribute("searchLN", "");
			    	session.setAttribute("searchY", "");
				}
		
		    	session.setAttribute("servletName", getServletName());
				
				String select = "select s from Student s where 1=1";
				if ((session.getAttribute("searchFN") != null) && (session.getAttribute("searchFN") != "")) 
					select += " and s.person.firstName like '%" + session.getAttribute("searchFN") + "%'";
				if ((session.getAttribute("searchLN") != null) && (session.getAttribute("searchLN") != "")) 
					select += "and s.person.lastName like '%" + session.getAttribute("searchLN") + "%'";
				if ((session.getAttribute("searchY") != null) && (session.getAttribute("searchY") != "")) 
					select += "and s.year = " + session.getAttribute("searchY");
				
				Query query = em.createQuery(select);
		    	int size = query.getResultList().size();
		    	
				request.setAttribute("size", size);
				
				if (size != 0) {   	
			    	action = request.getParameter("page");
			    	
			    	if (action == null) {
			    		session.setAttribute("pageBegin", 0);
			    		session.setAttribute("pageEnd", 19);
			    	} else {
			    		int begin = 0;
			    		int end = 19;
			    		
			    		try {
			    			begin = (Integer)session.getAttribute("pageBegin");
			    			end = (Integer)session.getAttribute("pageEnd");
			    		} catch (NullPointerException e) {}
			    		
			    		if (action.equals("next") && end+1 < size) {
			    			begin += 20;
			    			end += 20;
			    		} else if (action.equals("previous") && (begin > 0)) {
			    			begin -= 20;
			    			end -= 20;
			    		}
			    		
			    		session.setAttribute("pageBegin", begin);
			    		session.setAttribute("pageEnd", end);
			    	}
			    	
			    	query.setFirstResult((Integer)session.getAttribute("pageBegin"));
			    	query.setMaxResults(20);
			    	List<Student> students = query.getResultList();
			    	
					request.setAttribute("students", students);
				}

				request.setAttribute("id", id);
				request.getRequestDispatcher("/pages/rooms/roomStudents.jsp").forward(request, response);
			}			
			
			em.close();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session.setAttribute("searchFN", request.getParameter("searchFN"));
		session.setAttribute("searchLN", request.getParameter("searchLN"));
		session.setAttribute("searchY", request.getParameter("searchY"));
		
		this.doGet(request, response);
	}

}
